<?php

namespace App\Http\Model\Admin;

use Illuminate\Database\Eloquent\Model;

class Menu extends Model
{
    //  table name
    protected $table = 'menus';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'parent_id', 'url', 'route_name', 'name', 'remark', 'type', 'status', 'sort',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [

    ];

    /*
     *  has many roles
     * */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_menu', 'menu_id', 'role_id');
    }

    /**
     * find one by id
     *
     * @param  id
     * @return  model
     */
    public function findOneById($id)
    {
        $one = self::find($id);
        return $one;
    }

    /**
     * find one by name
     *
     * @param  name
     * @return  model
     */
    public function findOneByName($name = '')
    {
        $one = self::where('name', $name)->firstOrFail();
        return $one;
    }

    /**
     * find list by pageinate default 15
     *
     * @param  per_page
     * @return page info with model list
     */
    public function findAllByPaginate($per_page = 15)
    {
        $list = self::where('status', '<>', '0')->paginate($per_page);
        return $list;
    }

    /**
     * find all
     *
     *
     * @return model list
     */
    public function findAllValid()
    {
        $list = self::where('status', 1)->orderBy('sort', 'asc')->get();
        return $list;
    }


    /**
     * update one by id
     *
     * @param  id
     * @param  $input object
     * @return  boolean
     */
    public function updateOneById($id, $input)
    {
        return self::where('id', $id)->update($input);
    }

    /**
     * create new
     *
     * @param  input object
     * @return model
     */
    public function createNew($input)
    {
        return self::create($input);
    }

    /**
     * find by ids
     *
     * @param  ids array
     * @return model
     */
    public function findByIdArrs($ids)
    {
        return self::whereIn('id', $ids)->where('status',1)->orderBy('sort', 'asc')->get();
    }

    /**
     * delete by id
     *
     * @param  id
     * @return  bool
     */
    public function deleteById($id)
    {
        $p = self::where('id', $id)->update(['status' => 0]);
        $c = self::where('parent_id', $id)->update(['status' => 0]);
        return $p && $c;
    }

    /**
     * update by id
     *
     * @param  id
     * @return  bool
     */
    public function updateById($id, $input)
    {
        return self::where('id', $id)->update($input);
    }

}
